<template>
  <div :class="styles['picture-upload']" :style="{'--width': width || '80px', '--height': height || '80px'}">
    <el-image
        v-if="modelValue.url"
        preview-teleported
        :class="styles['img']"
        :src="modelValue.url"
        :max-scale="5"
        :min-scale="0.5"
        :preview-src-list="[modelValue.url]"
        fit="cover"
    />
    <Plus :class="styles['icon']" v-else @click="openUploadViewer"/>
    <CircleClose v-if="!disabled && modelValue.url" :class="styles['close']" @click="delFile"/>
    <el-dialog
        :class="styles['dialog']"
        v-model="modal.open"
        title="拍照界面示意图"
        width="452"
        center
        destroy-on-close
        append-to-body
    >
      <video v-if="modal.isPicturing" :class="styles['dialog-video']" ref="videoRef" autoplay :poster="VideoLinking"/>
      <img v-else :class="styles['img']" :src="modal.canvasUrl" alt="">
      <canvas ref="canvasRef" :class="styles['canvas']"></canvas>
      <div class="ato-flex-jc-sa">
        <el-button type="primary" v-if="modal.isPicturing" @click="takePhoto">拍照</el-button>
        <template v-else>
          <el-button type="plain" @click="onPicturing">拍照/重拍</el-button>
          <el-button type="primary" @click="uploadFile">使用照片</el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="PictureUpload">
import {nextTick, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import VideoLinking from '@/assets/images/video-linking.png'
import {
  updateCardImageApi,
  uploadCardImageApi,
  updateOrderImageApi,
  uploadOrderImageApi
} from '@/service/upload'
import { Plus, CircleClose } from '@element-plus/icons-vue'
import {useVideo} from '@/hooks'
import {base64URLtoFile} from '@/utils'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      url: '',
      uid: '',
      id: ''
    })
  },
  width: {
    type: String,
    default: '80px'
  },
  height: {
    type: String,
    default: '80px'
  },
  type: {
    type: String,
    default: 'card'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const modal = reactive({
  open: false, // 弹窗状态
  isPicturing: false, // 正在拍照中
  canvasUrl: ''
})

const videoRef = ref(null)
const canvasRef = ref(null)
const {openCamera, screenshot, stop} = useVideo(videoRef)

// 打开摄像头
function onPicturing () {
  modal.isPicturing = true
  nextTick(() => {
    openCamera()
  })
}
// 拍照
function takePhoto () {
  modal.canvasUrl = screenshot(canvasRef.value)
  modal.isPicturing = false
}
// 打开上传界面
function openUploadViewer () {
  modal.open = true
  if (!props.modelValue.url) {
    onPicturing()
  }
}
// 上传照片
async function uploadFile () {
  stop()
  // const res = await updatePictureApi(fileToUpload({videoFile: {
  //   id: 2,
  //   url: 'https://developcang.pokecolor.cn/media/warehouse/2024/09/3ef71672c8b21ac8cc50fbdef4762bfd.mp4'
  // }})) // 更新图片
  // console.log(res, 'video')
  if (!modal.canvasUrl) return
  const file = base64URLtoFile(modal.canvasUrl, Date.now() + '.jpeg')
  const {id, uid, url} = props.modelValue
  // 有两种上传图片：送卡订单合集图片、卡牌图片
  const upload = props.type === 'card' ? uploadCardImageApi : uploadOrderImageApi
  const update = props.type === 'card' ? updateCardImageApi : updateOrderImageApi

  // 判断id不存在新增图片upload，反正修改图片update
  const api = !id ? upload : update
  const res = await api({image: file, uid, id})
  if (res.code === 100) {
    const data = {
      id: res.data.id || id || '',
      url: res.data.image || url || '',
      uid
    }
    emit('update:modelValue', data)
    emit('change', data)
    ElMessage.success('上传成功')
    modal.open = false
  }
}
function delFile () {
  ElMessageBox.confirm('删除后，将无法恢复请确认是否执行', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    const data = {...props.modelValue, url: ''}
    emit('update:modelValue', data)
    emit('change', data)
  }
  )
}
</script>

<style lang="less" src="./index.less" module="styles">
</style>
